package com.ruoyi.web.controller.app;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * App端 用户个人信息接口
 *
 * @author laoguo
 */
@RestController
@RequestMapping("/app/user")
public class AppProfileController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取当前用户个人信息
     */
    @GetMapping("/profile")
    public AjaxResult getProfile() {
        // SecurityUtils 工具类可以方便地获取当前登录用户的信息
        Long userId = SecurityUtils.getUserId();
        SysUser user = userService.selectUserById(userId);

        // 为了安全，不返回密码等敏感信息，只返回前端需要的字段
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("nickname", user.getNickName());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("phonenumber", user.getPhonenumber());
        // 如果未来有会员体系，可以在这里添加 isVip, vipExpireTime 等字段

        return AjaxResult.success(userInfo);
    }

    /**
     * 修改当前用户个人信息
     */
    @PutMapping("/profile")
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        Long userId = SecurityUtils.getUserId();
        SysUser currentUser = userService.selectUserById(userId);

        currentUser.setNickName(user.getNickName());
        currentUser.setAvatar(user.getAvatar());
        currentUser.setUpdateBy(SecurityUtils.getUsername());

        if (userService.updateUserProfile(currentUser) > 0) {
            // **【核心步骤】** 更新成功后，刷新Redis中的缓存用户信息
            LoginUser loginUser = SecurityUtils.getLoginUser();
            loginUser.getUser().setNickName(currentUser.getNickName());
            loginUser.getUser().setAvatar(currentUser.getAvatar());
            tokenService.refreshToken(loginUser); // refreshToken内部会重新设置缓存

            return AjaxResult.success("修改成功");
        }

        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }
}